package com.gengine.resource
{
	import com.gengine.resource.loader.*;
	import flash.events.*;
	import flash.utils.*;
	
	public class ConfigManager extends EventDispatcher
	{
		private var _isLoaded:Boolean = false;
		private var _configDic:Dictionary;
		private static var _instance:ConfigManager;
		
		public function ConfigManager()
		{
			if (_instance != null)
			{
				throw new Error("ConfigManager 单例");
			}
			this._isLoaded = false;
		}
		
		public function load(url:String) : void
		{
			var loader:DataLoader = new DataLoader();
			loader.addEventListener(Event.COMPLETE, this.onLoadCompleteHandler);
			loader.addEventListener(ProgressEvent.PROGRESS, this.onLoadProgressHandler);
			loader.addEventListener(ErrorEvent.ERROR, this.onErrorHandler);
			loader.load(url);
		}
		
		private function onLoadCompleteHandler(event:Event) : void
		{
			this._isLoaded = true;
			var dataLoader:DataLoader = event.target as DataLoader;
			var bytes:* = dataLoader.bytesData;
			bytes.position = 0;
			bytes.uncompress();
			this._configDic = bytes.readObject() as Dictionary;
			dispatchEvent(event);
		}
		
		private function onLoadProgressHandler(event:ProgressEvent) : void
		{
			dispatchEvent(event);
		}
		
		private function onErrorHandler(event:ErrorEvent) : void
		{
			this._isLoaded = false;
			dispatchEvent(event);
		}
		
		public function getObjectByFileName(file:String) : Object
		{
			if (this.hasFile(file))
			{
				return this._configDic[file].content.root;
			}
			
			return null;
		}
		
		public function getStringByFileName(file:String) : String
		{
			if (this.hasFile(file))
			{
				return this._configDic[file].content;
			}
			return null;
		}
		
		public function getJSONByFileName(file:String) : Object
		{
			if (this.hasFile(file))
			{
				return this._configDic[file].content;
			}
			return null;
		}
		
		public function hasFile(file:String) : Boolean
		{
			if (this._isLoaded == false)
			{
				return false;
			}
			return this._configDic[file] != null;
		}
		
		public function getByteArrayByFileName(file:String) : ByteArray
		{
			if (this.hasFile(file))
			{
				return this._configDic[file].content as ByteArray;
			}
			return null;
		}
		
		public static function get instance() : ConfigManager
		{
			if (_instance == null)
			{
				_instance = new ConfigManager;
			}
			return _instance;
		}
	}
}
